/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.pig4cloud.pig.ads.pig.mapper.AdPlanMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdvMapper;
import com.pig4cloud.pig.ads.pig.mapper.AudiencePackageMapper;
import com.pig4cloud.pig.ads.service.*;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.AdPlan;
import com.pig4cloud.pig.api.entity.AudiencePackage;
import com.pig4cloud.pig.api.enums.*;
import com.pig4cloud.pig.api.util.AdvConstants;
import com.pig4cloud.pig.api.vo.AudiencePackageVo;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @广告账户 服务实现类
 * @author john
 *
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AudiencePackageServiceImpl extends ServiceImpl<AudiencePackageMapper, AudiencePackage> implements AudiencePackageService {

	private final AdUserAdverService adUserAdverService;

	private final TtAccesstokenService ttAccesstokenService;

	private final AudiencePackageMapper audiencePackageMapper;

	private final AdPlanMapper adPlanMapper;

	private final AdvMapper advMapper;

	@Autowired
	private AdvertiserService advertiserService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private AdvService advService;

	@Value("${audience_package_url_tt}")
	private String audiencePackageUrlTt;

/*








	@Override
	public Boolean removeAdvById(Integer id) {
		return convertTrackMapper.deleteAdvById(id) > 0;
	}*/




/*	@Override
	public ConvertTrack detail(Integer id) {
		ConvertTrack record = convertTrackMapper.selectById(id);
		//拉取并更新转化状态
		this.getAndUpdateStatus(record);
		return record;
	}*/


	@Override
	public R create(AudiencePackage entity) {
		//必需字段 非空检验
		if (StringUtils.isBlank(entity.getAdvertiserId())
				|| StringUtils.isBlank(entity.getName())
				|| StringUtils.isBlank(entity.getDescription())
				|| StringUtils.isBlank(entity.getLandingType()))
			return R.failed("advertiserId,name,description,landingType are all required");

		//数据校验
		R validateResult = this.dataValidate(entity);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		AudiencePackage recordInDb = this.getBaseMapper().selectByName(entity.getName());
		if (recordInDb!=null)
			return R.failed("名称 不能重复");

		entity.setPlatformId(Short.valueOf("1"));
		entity.setSyncStatus(Short.valueOf("0"));	//同步状态，默认 未同步
		if (StringUtils.isBlank(entity.getDeliveryRange())){
			entity.setDeliveryRange("DEFAULT");
		}
		entity.setCreatetime(new Date());

		if (!SqlHelper.retBool(this.getBaseMapper().insert(entity)))
			return R.failed("插入数据库失败");

		//在头条创建定向包
		R syncStatus = this.createInToutiao(entity);

		if (syncStatus.getCode() != CommonConstants.SUCCESS)
			return syncStatus;
		else
			return R.ok(null,"添加成功");

	}

	public <E extends IPage<AudiencePackage>> IPage<AudiencePackageVo> pagedAudiencePackage(E page, String[] advertiserIds) {
		//PigUser usr = SecurityUtils.getUser();
		Integer id = SecurityUtils.getUser().getId();

		//获取当前账号下 广告账户列表
		Map<String, String> adAccountMap = advService.getOwnerAdvMap(id, PlatformTypeEnum.TT.getValue());
		if(adAccountMap == null || adAccountMap.size() == 0) {
			return new Page();
		}


		QueryWrapper<AudiencePackage> wrapper = new QueryWrapper<>();
		wrapper.orderByDesc("id");
		if (adAccountMap.size()>0){
			wrapper.in("advertiser_id", adAccountMap.keySet());
		}else{
			wrapper.eq("advertiser_id", "-1");
		}
		if (advertiserIds != null && advertiserIds.length>0){
			wrapper.in("advertiser_id", advertiserIds);
		}
		IPage<AudiencePackage> result = this.getBaseMapper().selectPage(page, wrapper);

		List<AudiencePackageVo> voList = new ArrayList<>();
		for (AudiencePackage item : result.getRecords()){
			AudiencePackageVo itemVo = new AudiencePackageVo();
			BeanUtils.copyProperties(item, itemVo);

			//获取 advertiser name
			itemVo.setAdvertiserName(adAccountMap.get(item.getAdvertiserId()));

			//统计 绑定计划个数
			int adPlanCount = adPlanMapper.selectCount(Wrappers.<AdPlan>query().lambda().eq(AdPlan::getAudienceId,Long.valueOf(item.getId())));
			itemVo.setAdPlanCount(adPlanCount);

			voList.add(itemVo);
		}

		IPage<AudiencePackageVo> voPage = new Page<AudiencePackageVo>(result.getCurrent(),result.getSize(),result.getTotal());
		voPage.setRecords(voList);
		return voPage;
	}


	@Override
	public IPage<AudiencePackageVo> pagedAudiencePackageSycSuc(Page page, QueryWrapper<AudiencePackage> wrapper) {

		IPage<AudiencePackage> result = this.getBaseMapper().selectPage(page, wrapper);

		log.info("result=={}", JSON.toJSONString(result));

		List<AudiencePackageVo> voList = new ArrayList<>();
		if(result != null && result.getRecords() != null && result.getRecords().size() > 0){
			for (AudiencePackage item : result.getRecords()){
				AudiencePackageVo itemVo = new AudiencePackageVo();
				BeanUtils.copyProperties(item, itemVo);

				//拉取并更新转化状态
				int adPlanCount = adPlanMapper.selectCount(Wrappers.<AdPlan>query().lambda().eq(AdPlan::getAudienceId,item.getId().longValue()));
				itemVo.setAdPlanCount(adPlanCount);

				voList.add(itemVo);
			}
		}

		IPage<AudiencePackageVo> voPage = new Page<AudiencePackageVo>(result.getCurrent(),result.getSize(),result.getTotal());
		voPage.setRecords(voList);
		return voPage;
	}


	@Override
	public AudiencePackage detail(Integer id) {
		AudiencePackage record = this.getBaseMapper().selectById(id);
		return record;
	}

	@Override
	public R remove(Integer id) {
		AudiencePackage ap = audiencePackageMapper.selectById(id);
		if (ap == null)
			return R.failed("定向包不存在!!!");

		List<AdPlan> adPlans = adPlanMapper.selectList(Wrappers.<AdPlan>query().lambda().eq(AdPlan::getAudienceId,Long.valueOf(id)));
		List<Long> strAds = new ArrayList<>();
		adPlans.forEach(item -> {
			strAds.add(Long.valueOf(item.getAdId()));
		});

		R unbindResult = this.unbindAdplan(id, strAds);
		if (unbindResult.getCode() != CommonConstants.SUCCESS)
			return unbindResult.setMsg("删除时,解绑广告计划失败:" + unbindResult.getMsg());

		R deleteResult = this.deleteInToutiao(ap);
		if (deleteResult.getCode() != CommonConstants.SUCCESS)
			return unbindResult.setMsg("从头条删除失败:" + unbindResult.getMsg());

		//删除广告计划
		boolean result = SqlHelper.retBool(this.getBaseMapper().deleteById(id));
		if (result)
			return R.ok(null,"成功删除");
		else
			return R.ok(null,"成功解绑广告计划,但未从数据库删除");
	}

	@Override
	public R bindAdplan(Integer audiencePackageId, List<Long> ads) {
		AudiencePackage ap = this.baseMapper.selectById(audiencePackageId);
		if (ap == null)
			return R.failed("定向包不存在!!!");

		List<String> toutiaoAdIds = new ArrayList<>();
		for (Long adid : ads){
			AdPlan adplan = adPlanMapper.selectById(adid);

			if (adplan == null)
				return R.failed(String.format("广告计划[%d] 不存在!!!", adid));

			toutiaoAdIds.add(String.valueOf(adplan.getAdId()));
		}

		//1、请求头条，进行绑定
		R syncResult = this.bindAdsInToutiao(ap, toutiaoAdIds);
		if (syncResult.getCode() != CommonConstants.SUCCESS)
			return syncResult;

		//2、将关系落地数据库
		for (Long adid : ads){
			AdPlan tmp = new AdPlan();
			tmp.setAudienceId(Long.valueOf(audiencePackageId));
			tmp.setAdId(adid);

			adPlanMapper.updateById(tmp);
		}


		return R.ok(null, "绑定成功");
	}

	@Override
	public R unbindAdplan(Integer audiencePackageId, List<Long> ads) {
		AudiencePackage ap = this.baseMapper.selectById(audiencePackageId);
		if (ap == null)
			return R.failed("定向包不存在!!!");

		List<String> toutiaoAdIds = new ArrayList<>();
		for (Long adid : ads){
			AdPlan adplan = adPlanMapper.selectById(adid);

			if (adplan == null)
				return R.failed(String.format("广告计划[%d] 不存在!!!", adid));

			toutiaoAdIds.add(String.valueOf(adplan.getAdId()));
		}

		//1、请求头条，进行解绑
		R syncResult = this.unbindAdsInToutiao(ap, toutiaoAdIds);
		if (syncResult.getCode() != CommonConstants.SUCCESS)
			return syncResult;

		//2、将关系落地数据库
		AdPlan updatePlan=null;
		for (Long adid : ads){
			updatePlan=new AdPlan();
			updatePlan.setAudienceId(null);
			updatePlan.setAdId(adid);
			adPlanMapper.updateById(updatePlan);
		}

		return R.ok(null, "解绑成功");
	}

	@Override
	public R update(AudiencePackage entity) {
		//必需字段 非空检验
		if (entity.getId() == null
				|| StringUtils.isBlank(entity.getAdvertiserId())
				|| StringUtils.isBlank(entity.getDescription()))
			return R.failed("id,advertiserId,description are all required");

		AudiencePackage recordOld = this.getBaseMapper().selectById(entity.getId());
		if (recordOld == null)
			return R.failed(String.format("定向包[%d]不存在!!!", entity.getId()));

		//1、更新toutiao 中的定向包
		R uptResult = this.updateInToutiao(entity, recordOld);
		if (uptResult.getCode() != CommonConstants.SUCCESS)
			return uptResult;

		//2、更新到数据库
		if (!SqlHelper.retBool(audiencePackageMapper.updateByPrimaryKeySelectivePartial(entity)))
			R.failed("头条更新成功,落地数据库失败!!!");

		//3、更新到广告计划

		return R.ok(null, "更新成功");
	}

	//---------------------------------------------------------

	private R createInToutiao(AudiencePackage entity){
		//数据校验
		R validateResult = this.dataValidate(entity);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		String token = ttAccesstokenService.fetchAccesstoken(entity.getAdvertiserId());		  //this.getAccesstoken(entity);

		//调用头条接口
		Map<String, Object> data = this.entityToMap(entity);
		String resultStr = OEHttpUtils.doPost(audiencePackageUrlTt + "create/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("同步到投放平台失败");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			AudiencePackage tmp = new AudiencePackage();
			tmp.setId(entity.getId());
			tmp.setSyncStatus(Short.valueOf("2"));

			audiencePackageMapper.updateByPrimaryKeySelective(tmp);		//更新失败状态到db
			return R.failed("同步到投放平台失败:" + this.chineseMsg(obj.getString("message")));
		}

		//若同步成功	跟更新状态到数据库
		String dataStr = obj.getString("data");
		JSONObject dataObj = JSON.parseObject(dataStr);

		AudiencePackage tmp = new AudiencePackage();
		tmp.setId(entity.getId());
		tmp.setIdAdPlatform(dataObj.getString("audience_package_id"));
		tmp.setSyncStatus(Short.valueOf("1"));		//同步成功
		if (!SqlHelper.retBool(audiencePackageMapper.updateByPrimaryKeySelective(tmp)))
			return R.failed("同步到投放平台后，更新状态失败");

		return R.ok(null,"成功同步到投放平台");
	}

	private R updateInToutiao(AudiencePackage eNew, AudiencePackage eOld){
		if (StringUtils.isBlank(eOld.getIdAdPlatform()))
			return R.failed(String.format("定向包[%d]在头条不存在!!!", eOld.getIdAdPlatform()));

		R validateResult = this.dataValidate(eNew);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		Map<String, Object> data = this.entityToMapForUpt(eNew);
		data.put("audience_package_id", eOld.getIdAdPlatform());

		String token = ttAccesstokenService.fetchAccesstoken(eNew.getAdvertiserId());		  //this.getAccesstoken(entity);
		String resultStr = OEHttpUtils.doPost(audiencePackageUrlTt + "update/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("更新到投放平台失败");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("更新到投放平台失败:" + this.chineseMsg(obj.getString("message")));
		}

		//若同步成功	跟更新状态到数据库
		return R.ok(null,"更新到头条成功");
	}

	private R deleteInToutiao(AudiencePackage entity){
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", entity.getAdvertiserId());
		data.put("audience_package_id", entity.getIdAdPlatform());

		String token = ttAccesstokenService.fetchAccesstoken(entity.getAdvertiserId());				//this.getAccesstoken(entity);
		//String accessToken = "3e09cc34a5812083ad9bd2f9eca6659fe2aadaa6";

		//调用头条接口
		String resultStr = OEHttpUtils.doPost(audiencePackageUrlTt + "delete/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("在toutiao删除失败 ");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("在toutiao删除失败");
		}else{
			return R.ok(null, "在toutiao删除成功");
		}


		//return R.ok("");
	}

	private R bindAdsInToutiao(AudiencePackage entity, List<String> ads){
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", entity.getAdvertiserId());
		data.put("audience_package_id", entity.getIdAdPlatform());
		data.put("ad_ids", ads.toArray());

		String token = ttAccesstokenService.fetchAccesstoken(entity.getAdvertiserId());		   //this.getAccesstoken(entity);
		//String accessToken = "3e09cc34a5812083ad9bd2f9eca6659fe2aadaa6";

		//调用头条接口
		String resultStr = OEHttpUtils.doPost(audiencePackageUrlTt + "ad/bind/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("在toutiao绑定失败 ");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("在toutiao绑定失败");
		}else{
			return R.ok(null, "在toutiao绑定成功");
		}
	}

	private R unbindAdsInToutiao(AudiencePackage entity, List<String> ads){
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", entity.getAdvertiserId());
		data.put("audience_package_id", entity.getIdAdPlatform());
		data.put("ad_ids", ads.toArray());

		String token = ttAccesstokenService.fetchAccesstoken(entity.getAdvertiserId());			//this.getAccesstoken(entity);
		//String accessToken = "3e09cc34a5812083ad9bd2f9eca6659fe2aadaa6";

		//调用头条接口
		String resultStr = OEHttpUtils.doPost(audiencePackageUrlTt + "ad/unbind/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("在toutiao解绑失败 ");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("在toutiao解绑失败");
		}else{
			return R.ok(null, "在toutiao解绑成功");
		}
	}



	/**
	 * 根据广告账号查询对应授权token
	 * @param entity
	 * @return
	 */
/*	private String getAccesstoken(AudiencePackage entity){
		AdvertiserInfo advertiserInfo=  advertiserMapper.selectAdvertiserByAdAccount(entity.getAdvertiserId());
		String housekeeper = advertiserInfo.getHousekeeper();

		//根据housekeeper获取accessToken
		String tokenContent = stringRedisTemplate.opsForValue().get(Constants.OCEANENGINE_REDIS_TOKEN_KEY_PRIX_ + housekeeper);
		Accesstoken accessToken = JSON.parseObject(tokenContent, Accesstoken.class);
		String token = accessToken.getAccessToken();

		token = "d93a80eb230e78a9de7eff1236232b5a21b2ea37";			//test code
		return token;
	}*/

	private Map<String, Object> entityToMap(AudiencePackage entity){
		Map<String, Object> data = new HashMap<String, Object>();

		//required 字段
		data.put("advertiser_id", entity.getAdvertiserId());
		data.put("name", entity.getName());
		data.put("description", entity.getDescription());
		data.put("landing_type", entity.getLandingType());

		data.put("auto_extend_enabled", 0);
		data.put("delivery_range", 1);
		data.put("hide_if_exists", 0);
		data.put("hide_if_converted", 0);
		data.put("interest_tag_mode", 0);


		//非必须 字段
		if (StringUtils.isNotBlank(entity.getDeliveryRange()))
			data.put("delivery_range", entity.getDeliveryRange());

		if (StringUtils.isNotBlank(entity.getDistrict()))
			data.put("district", entity.getDistrict());

/*		if (StringUtils.isNotBlank(entity.getProvince()))
			data.put("province", entity.getProvince());*/

		if (StringUtils.isNotBlank(entity.getCity()))
			data.put("city", entity.getCity());

		if (StringUtils.isNotBlank(entity.getBusinessIds()))
			data.put("business_ids", entity.getBusinessIds());

		if (StringUtils.isNotBlank(entity.getLocationType()))
			data.put("location_type", entity.getLocationType());

		if (StringUtils.isNotBlank(entity.getGender()))
			data.put("gender", entity.getGender());

		if (entity.getAge() !=null)
			data.put("age", entity.getAge().split(","));

		if (StringUtils.isNotBlank(entity.getRetargetingTags()))
			data.put("retargeting_tags", entity.getRetargetingTags().split(","));


		if (StringUtils.isNotBlank(entity.getRetargetingTagsExclude()))
			data.put("retargeting_tags_exclude", entity.getRetargetingTagsExclude().split(","));


		if (StringUtils.isNotBlank(entity.getInterestActionMode()))
			data.put("interest_action_mode", entity.getInterestActionMode());

		if (StringUtils.isNotBlank(entity.getAwemeFanBehaviors()))
			data.put("aweme_fan_behaviors", entity.getAwemeFanBehaviors().split(","));

		if (StringUtils.isNotBlank(entity.getAwemeFanCategories()))
			data.put("aweme_fan_categories", entity.getAwemeFanCategories());

		if (StringUtils.isNotBlank(entity.getAwemeFanAccounts()))
			data.put("aweme_fan_accounts", entity.getAwemeFanAccounts());

		if (entity.getAwemeFanTimeScope() != null)
			data.put("aweme_fan_time_scope", entity.getAwemeFanTimeScope());

		if (entity.getPlatform() !=null) {
			String[] arr = entity.getPlatform().split(",");

			Object[] toutiaoVals = Arrays.stream(arr).map(item -> ToutiaoPlatformEnum.valueByType(item))
					.collect(Collectors.toList()).toArray();

			data.put("platform",toutiaoVals);
		};

		if ( StringUtils.isNotBlank(entity.getAc())){
			String[] arr = entity.getAc().split(",");

			Object[] toutiaoVals = Arrays.stream(arr).map(item -> ToutiaoAcEnum.valueByType(item))
					.collect(Collectors.toList()).toArray();

			data.put("ac",toutiaoVals);
		}


		if (entity.getHideIfExists() !=null)
			data.put("hide_if_exists", entity.getHideIfExists());

		if (entity.getHideIfConverted() !=null)
			data.put("hide_if_converted", entity.getHideIfConverted());

		if (entity.getConvertedTimeDuration() !=null)
			data.put("converted_time_duration", entity.getConvertedTimeDuration());

		if (StringUtils.isNotBlank(entity.getAndroidOsv()))
			data.put("android_osv", entity.getAndroidOsv());

		if (entity.getCarrier() !=null)
			data.put("carrier", entity.getCarrier().split(","));

		if (entity.getActivateType() !=null)
			data.put("activate_type", entity.getActivateType().split(","));

		if (entity.getDeviceBrand() !=null)
			data.put("device_brand", entity.getDeviceBrand().split(","));

		if (entity.getLaunchPriceFrom() !=null || entity.getLaunchPriceTo() !=null){
			Integer from = AdvConstants.LaunchPriceMin;
			Integer to = AdvConstants.LaunchPriceMax;

			if (entity.getLaunchPriceFrom() !=null && entity.getLaunchPriceFrom() > from){
				from = entity.getLaunchPriceFrom();
			}
			if (entity.getLaunchPriceTo() != null && entity.getLaunchPriceTo() <to){
				to = entity.getLaunchPriceTo();
			}
			Integer[] boundry = {from, to};
			data.put("launch_price", boundry);
		}

		if (entity.getCareer() !=null)
			data.put("career", entity.getCareer().split(","));

		if (entity.getAutoExtendEnabled() !=null)
			data.put("auto_extend_enabled", entity.getAutoExtendEnabled());

		if (StringUtils.isNotBlank(entity.getDistrict()))
			data.put("district", entity.getDistrict());

		if (StringUtils.isNotBlank(entity.getProvince())){
			data.put("province", entity.getProvince().split(","));
		}

		if (StringUtils.isNotBlank(entity.getCity())){
			data.put("city", entity.getCity().split(","));
		}

		if (StringUtils.isNotBlank(entity.getBusinessIds())){
			data.put("business_ids", entity.getBusinessIds().split(","));
		}

		if (StringUtils.isNotBlank(entity.getLocationType())){
			data.put("location_type", entity.getLocationType());
		}

		if (StringUtils.isNotBlank(entity.getInterestActionMode())){
			data.put("interest_action_mode", entity.getInterestActionMode());
		}

		if (StringUtils.isNotBlank(entity.getArticleCategory()))
			data.put("article_category", entity.getArticleCategory().split(","));

		if (StringUtils.isNotBlank(entity.getActionScene()))
			data.put("action_scene", entity.getActionScene().split(","));

		if (entity.getActionDays() != null)
			data.put("action_days", entity.getActionDays());

		if (StringUtils.isNotBlank(entity.getActionCategories()))
			data.put("action_categories", entity.getActionCategories().split(","));

		if (StringUtils.isNotBlank(entity.getActionWords()))
			data.put("action_words", entity.getActionWords().split(","));

		if (StringUtils.isNotBlank(entity.getInterestCategories()))
			data.put("interest_categories", entity.getInterestCategories().split(","));

		if (StringUtils.isNotBlank(entity.getInterestWords()))
			data.put("interest_words", entity.getInterestWords().split(","));

		return data;
	}

	private Map<String, Object> entityToMapForUpt(AudiencePackage entity){
		Map<String, Object> data = new HashMap<String, Object>();

		//required 字段
		data.put("advertiser_id", entity.getAdvertiserId());
		data.put("name", entity.getName());
		data.put("description", entity.getDescription());
		data.put("landing_type", entity.getLandingType());

		data.put("auto_extend_enabled", 0);
		data.put("delivery_range", 1);
		data.put("hide_if_exists", 0);
		data.put("hide_if_converted", 0);
		data.put("interest_tag_mode", 0);


		//非必须 字段
		if (StringUtils.isNotBlank(entity.getDeliveryRange()))
			data.put("delivery_range", entity.getDeliveryRange());

		if (StringUtils.isNotBlank(entity.getDistrict()))
			data.put("district", entity.getDistrict());
		else
			data.put("district","NONE");

/*		if (StringUtils.isNotBlank(entity.getProvince()))
			data.put("province", entity.getProvince());*/

		if (StringUtils.isNotBlank(entity.getCity()))
			data.put("city", entity.getCity());

		if (StringUtils.isNotBlank(entity.getBusinessIds()))
			data.put("business_ids", entity.getBusinessIds());

		if (StringUtils.isNotBlank(entity.getLocationType()))
			data.put("location_type", entity.getLocationType());

		if (StringUtils.isNotBlank(entity.getGender()))
			data.put("gender", entity.getGender());
		else
			data.put("gender","NONE");

		if (entity.getAge() !=null)
			data.put("age", entity.getAge().split(","));
		else
			data.put("age", new String[0]);

		if (StringUtils.isNotBlank(entity.getRetargetingTags()))
			data.put("retargeting_tags", entity.getRetargetingTags().split(","));
		else{
			data.put("retargeting_tags", new String[0]);
		}


		if (StringUtils.isNotBlank(entity.getRetargetingTagsExclude()))
			data.put("retargeting_tags_exclude", entity.getRetargetingTagsExclude().split(","));
		else
			data.put("retargeting_tags_exclude",new String[0]);


		if (StringUtils.isNotBlank(entity.getInterestActionMode()))
			data.put("interest_action_mode", entity.getInterestActionMode());
		else
			data.put("interest_action_mode","UNLIMITED");

		if (StringUtils.isNotBlank(entity.getAwemeFanBehaviors()))
			data.put("aweme_fan_behaviors", entity.getAwemeFanBehaviors().split(","));

		if (StringUtils.isNotBlank(entity.getAwemeFanCategories()))
			data.put("aweme_fan_categories", entity.getAwemeFanCategories());

		if (StringUtils.isNotBlank(entity.getAwemeFanAccounts()))
			data.put("aweme_fan_accounts", entity.getAwemeFanAccounts());

		if (entity.getAwemeFanTimeScope() != null)
			data.put("aweme_fan_time_scope", entity.getAwemeFanTimeScope());

		if (entity.getPlatform() !=null) {
			String[] arr = entity.getPlatform().split(",");

			Object[] toutiaoVals = Arrays.stream(arr).map(item -> ToutiaoPlatformEnum.valueByType(item))
					.collect(Collectors.toList()).toArray();

			data.put("platform",toutiaoVals);
		}else{
			data.put("platform",new String[0]);
		}

		if ( StringUtils.isNotBlank(entity.getAc())){
			String[] arr = entity.getAc().split(",");

			Object[] toutiaoVals = Arrays.stream(arr).map(item -> ToutiaoAcEnum.valueByType(item))
					.collect(Collectors.toList()).toArray();

			data.put("ac",toutiaoVals);
		}else{
			data.put("ac",new String[0]);
		}


		if (entity.getHideIfExists() !=null)
			data.put("hide_if_exists", entity.getHideIfExists());
		else
			data.put("hide_if_exists",0);

		if (entity.getHideIfConverted() !=null)
			data.put("hide_if_converted", entity.getHideIfConverted());

		if (entity.getConvertedTimeDuration() !=null)
			data.put("converted_time_duration", entity.getConvertedTimeDuration());

		if (StringUtils.isNotBlank(entity.getAndroidOsv()))
			data.put("android_osv", entity.getAndroidOsv());
		else
			data.put("android_osv","0.0");

		if (entity.getCarrier() !=null)
			data.put("carrier", entity.getCarrier().split(","));
		else
			data.put("carrier",new String[0]);

		if (entity.getActivateType() !=null)
			data.put("activate_type", entity.getActivateType().split(","));
		else
			data.put("activate_type",new String[0]);

		if (entity.getDeviceBrand() !=null)
			data.put("device_brand", entity.getDeviceBrand().split(","));
		else
			data.put("device_brand",new String[0]);

		if (entity.getLaunchPriceFrom() !=null || entity.getLaunchPriceTo() !=null){
			Integer from = AdvConstants.LaunchPriceMin;
			Integer to = AdvConstants.LaunchPriceMax;

			if (entity.getLaunchPriceFrom() !=null && entity.getLaunchPriceFrom() > from){
				from = entity.getLaunchPriceFrom();
			}
			if (entity.getLaunchPriceTo() != null && entity.getLaunchPriceTo() <to){
				to = entity.getLaunchPriceTo();
			}
			Integer[] boundry = {from, to};
			data.put("launch_price", boundry);
		}

		if (entity.getCareer() !=null)
			data.put("career", entity.getCareer().split(","));

		if (entity.getAutoExtendEnabled() !=null)
			data.put("auto_extend_enabled", entity.getAutoExtendEnabled());

		if (StringUtils.isNotBlank(entity.getCity())){
			data.put("city", entity.getCity().split(","));
		}

		if (StringUtils.isNotBlank(entity.getBusinessIds())){
			data.put("business_ids", entity.getBusinessIds().split(","));
		}

		if (StringUtils.isNotBlank(entity.getLocationType())){
			data.put("location_type", entity.getLocationType());
		}

		if (StringUtils.isNotBlank(entity.getArticleCategory()))
			data.put("article_category", entity.getArticleCategory().split(","));
		else
			data.put("article_category", new String[0]);

		if (StringUtils.isNotBlank(entity.getActionScene()))
			data.put("action_scene", entity.getActionScene().split(","));

		if (entity.getActionDays() != null)
			data.put("action_days", entity.getActionDays());

		if (StringUtils.isNotBlank(entity.getActionCategories()))
			data.put("action_categories", entity.getActionCategories().split(","));
		else
			data.put("action_categories", new String[0]);

		if (StringUtils.isNotBlank(entity.getActionWords()))
			data.put("action_words", entity.getActionWords().split(","));
		else
			data.put("action_words", new String[0]);

		if (StringUtils.isNotBlank(entity.getInterestCategories()))
			data.put("interest_categories", entity.getInterestCategories().split(","));
		else
			data.put("interest_categories", new String[0]);

		if (StringUtils.isNotBlank(entity.getInterestWords()))
			data.put("interest_words", entity.getInterestWords().split(","));
		else
			data.put("interest_words", new String[0]);

		return data;
	}

	private R dataValidate(AudiencePackage entity){

		if (StringUtils.isNotBlank(entity.getName())
				&&entity.getName().length() > 100)
			return R.failed("定向包名称过长");

		if (StringUtils.isNotBlank(entity.getDescription())
				&&entity.getDescription().length() > 1500)
			return R.failed("描述过长");

		if (StringUtils.isNotBlank(entity.getLandingType()) &&
				!ToutiaoAPLandTypeEnum.containsType(entity.getLandingType()))
			return R.failed("未知的 定向包类型 !!!");

		if (StringUtils.isNotBlank(entity.getDeliveryRange()) &&
				!ToutiaoDeliveryRangeEnum.containsType(entity.getDeliveryRange()))
			return R.failed("未知的 投放范围 !!!");

		if (StringUtils.isNotBlank(entity.getGender())){
			if (!ToutiaoGenderEnum.containsType(entity.getGender()))
				return R.failed("未知的 性别 !!!");
		}

		if (StringUtils.isNotBlank(entity.getAge())){
			String[] arr = entity.getAge().split(",");
			for (String item : arr){
				if (!ToutiaoAgeEnum.containsType(item)){
					return R.failed("未知的 年龄 !!!");
				}
			}
		}

		if (StringUtils.isNotBlank(entity.getPlatform())){
			String[] arr = entity.getPlatform().split(",");
			for (String item : arr){
				if (!ToutiaoPlatformEnum.containsType(item)){
					return R.failed("未知的 平台 !!!");
				}
			}
		}

		if (StringUtils.isNotBlank(entity.getAc())){
			String[] arr = entity.getAc().split(",");
			for (String item : arr){
				if (!ToutiaoAcEnum.containsType(item)){
					return R.failed("未知的 网络类型 !!!");
				}
			}
		}

		if (entity.getHideIfExists() != null
				&& !ToutiaoHideIfExistsEnum.containsType(String.valueOf(entity.getHideIfExists()))){
			return R.failed("已安装用户 选项不合法 !!!");
		}

		if (entity.getHideIfConverted() != null
				&& !ToutiaoHideIfConvertedEnum.containsType(String.valueOf(entity.getHideIfConverted()))){
			return R.failed("unknown hideIfConverted type !!!");
		}

		if (entity.getConvertedTimeDuration() !=null
				&& !ToutiaoConvertedTimeDurationEnum.containsType(String.valueOf(entity.getConvertedTimeDuration()))){
			return R.failed("unknown convertedTimeDuration type !!!");
		}

		if (StringUtils.isNotBlank(entity.getAndroidOsv())
				&& !ToutiaoAndroidVersionEnum.containsType(entity.getAndroidOsv())){
			return R.failed("未知的 安卓版本 !!!");
		}

		if (StringUtils.isNotBlank(entity.getCarrier())){
			String[] arr = entity.getCarrier().split(",");
			for (String item : arr){
				if (!ToutiaoCarrierEnum.containsType(item)){
					return R.failed("未知的 运营商 !!!");
				}
			}
		}

		if (StringUtils.isNotBlank(entity.getActivateType())){
			String[] arr = entity.getActivateType().split(",");
			for (String item : arr){
				if (!ToutiaoActivateTypeEnum.containsType(item)){
					return R.failed("新用户 选项不合法 !!!");
				}
			}
		}

		if (StringUtils.isNotBlank(entity.getDeviceBrand())){
			String[] arr = entity.getDeviceBrand().split(",");
			for (String item : arr){
				if (!ToutiaoDeviceBrandEnum.containsType(item)){
					return R.failed("未知的 设备品牌 !!!");
				}
			}
		}

		if (StringUtils.isNotBlank(entity.getCareer())){
			String[] arr = entity.getCareer().split(",");
			for (String item : arr){
				if (!ToutiaoCareerEnum.containsType(item)){
					return R.failed("unknown career type !!!");
				}
			}
		}

		//手机价格校验
		if (entity.getLaunchPriceFrom() !=null || entity.getLaunchPriceTo() !=null){
			Integer from = AdvConstants.LaunchPriceMin;
			Integer to = AdvConstants.LaunchPriceMax;

			if (entity.getLaunchPriceFrom() !=null){
				if (!ToutiaoDevicePriceEnum.containsType(String.valueOf(entity.getLaunchPriceFrom())))
					return R.failed("不合法的手机价格");
				if (entity.getLaunchPriceFrom() > from)
					from = entity.getLaunchPriceFrom();
			}
			if (entity.getLaunchPriceTo() != null){
				if (!ToutiaoDevicePriceEnum.containsType(String.valueOf(entity.getLaunchPriceTo())))
					return R.failed("不合法的手机价格");
				if (entity.getLaunchPriceTo() <to)
					to = entity.getLaunchPriceTo();
			}
			if (from > to)
				return R.failed("手机价格 边界异常");
		}

		//人群包检验
		if (StringUtils.isNotBlank(entity.getRetargetingTags())){
			String[] arr = entity.getRetargetingTags().split(",");
			for (String item : arr){
				if (!StringUtils.isNumeric(item))
					return R.failed("非法的人群包id[%s]", item);
			}
		}
		if (StringUtils.isNotBlank(entity.getRetargetingTagsExclude())){
			String[] arr = entity.getRetargetingTagsExclude().split(",");
			for (String item : arr){
				if (!StringUtils.isNumeric(item))
					return R.failed("非法的人群包id[%s]", item);
			}
		}

		if (StringUtils.isNotBlank(entity.getDistrict())
				&& !ToutiaoDistrictLevelEnum.containsType(entity.getDistrict()))
			return R.failed("未知的 区域类型!!!");

		if (StringUtils.isNotBlank(entity.getLocationType())
				&& !ToutiaoLocationTypeEnum.containsType(entity.getLocationType())){
			return R.failed("未知的 受众位置类型!!!");
		}

		if (StringUtils.isNotBlank(entity.getInterestActionMode())
				&& !ToutiaoInterestActionModeEnum.containsType(entity.getInterestActionMode())){
			return R.failed("位置的 行为兴趣 选项!!!");
		}



		//if (StringUtils.isNotBlank())

		//if (StringUtils.isNotBlank(entity.getPlatform()))

		return R.ok(null,"验证通过");
	}

	private String chineseMsg(String msg){
		for (ToutiaoAudiencePackageFieldsEnum field : ToutiaoAudiencePackageFieldsEnum.values()){
			String replaceStr = String.format("%s:",field.getType());
			if (msg.contains(replaceStr)){
				msg = msg.replace(replaceStr, field.getName());
				break;
			}
		}
		return msg;
	}


}
